<template>
  <div style="height: auto">
    <!-- 头部搜索 -->
    <el-card style="width: 100%; margin-bottom: 10px" shadow="never">
      <el-row>
        <el-col :span="3">
          <el-date-picker
            v-model="ordDto.time"
            type="date"
            placeholder="派工日期"
            value-format="YYYY-MM-DD"
            style="width: 160px"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="ordDto.dispatchingNumber"
            style="width: 120px"
            placeholder="配送订单号"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="ordDto.vehicleNumber"
            style="width: 120px"
            placeholder="车辆自编号"
            clearable
          >
          </el-input>
        </el-col>

        <el-col :span="2">
          <el-input
            v-model="ordDto.licenseNumber"
            style="width: 120px"
            placeholder="车牌号"
            clearable
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="ordDto.name"
            style="width: 120px"
            placeholder="人员名称"
            clearable
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="ordDto.tel"
            style="width: 120px"
            placeholder="驾驶员电话"
            clearable
          />
        </el-col>

        <el-col
          style="display: flex; justify-content: flex-end; align-items: center"
          :span="2"
        >
          <el-space :size="20">
            <el-button type="primary" plain size="small" @click="handleSearch"
              >搜索</el-button
            >
            <el-button type="danger" plain size="small">重置</el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格数据展示 EEF7FD -->
    <el-alert :title="title" type="error" :closable="false" />
    <!-- #A2CBF8 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 1%">
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="dispatchingNumber"
        label="派工大单号"
        width="120"
        align="center"
      />
      <el-table-column
        prop="dispatcher"
        label="调度人员"
        width="120"
        align="center"
      />

      <el-table-column
        prop="vehicleNumber"
        label="自编号"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="licenseNumber"
        label="车牌号码"
        align="center"
        width="120"
      ></el-table-column>

      <el-table-column prop="driver" label="驾驶员" align="center">
        <template #default="scope">
          <el-tag
            type="primary"
            v-for="item in scope.row.personnels"
            :key="item.id"
          >
            {{ item.name }} {{ item.position }} {{ item.tel }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="poll" label="票数" align="center" width="80" />
      <el-table-column prop="complete" label="完成" align="center" width="80">
        <template #default="scope">
          <text style="color: #67c23a; font-weight: bold">{{
            scope.row.complete
          }}</text>
        </template>
      </el-table-column>

      <el-table-column label="剩余" align="center" width="80">
        <template #default="scope">
          <text style="color: #f56c6c; font-weight: bold">
            {{ scope.row.poll - scope.row.complete }}</text
          >
        </template>
      </el-table-column>

      <el-table-column prop="volume" label="总体积" align="center" width="120">
      </el-table-column>

      <el-table-column
        prop="dispatchTime"
        label="预派工时间"
        align="center"
        width="120"
      />

      <el-table-column
        prop="determineTime"
        label="确认时间"
        align="center"
        width="120"
      />

      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="120"
      />

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            :icon="User"
            type="primary"
            size="small"
            v-has="`btn:user:per:role`"
            @click="handleRole(scope.row)"
          >
            查看
          </el-button>
          <el-button
            v-has="`btn:user:update`"
            :icon="Edit"
            type="warning"
            size="small"
            @click="handlePrint(scope.row)"
            >打印</el-button
          >
          <el-button
            v-has="`btn:user:update`"
            :icon="Edit"
            type="success"
            size="small"
            @click="handlelock(scope.row)"
            >确定</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      v-model="drawer"
      title="派工详情"
      :direction="direction"
      size="70%"
    >
      <el-select
        v-model="seldriver"
        placeholder="选择驾驶员"
        style="width: 120px"
      >
        <el-option
          v-for="item in carList"
          :key="item.id"
          :label="item.licenseNumber"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="selworke"
        multiple
        clearable
        filterable
        placeholder="选择工人"
        style="width: 240px"
      >
        <el-option
          v-for="item in perList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-button
        :icon="User"
        type="danger"
        v-has="`btn:user:per:role`"
        @click="handleUpdateCar()"
      >
        更新车组
      </el-button>

      <el-button
        :icon="User"
        type="pr"
        v-has="`btn:user:per:role`"
        @click="handleAddOrder"
      >
        加派订单
      </el-button>

      <el-table :data="list" border style="width: 100%; margin-top: 1%">
        <el-table-column
          prop="orderNumber"
          label="服务单号"
          align="center"
          width="130"
        />
        <!-- <el-table-column prop="orderNumber" label="送货单号" align="center" /> -->
        <el-table-column
          prop="username"
          label="客户"
          width="150"
          align="center"
        />

        <el-table-column
          prop="address"
          label="地址"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="zxstorage"
          label="自选"
          align="center"
          width="60"
        />
        <el-table-column
          prop="wcstorage"
          label="外仓"
          align="center"
          width="60"
        />
        <el-table-column prop="total" label="合计" align="center" width="60" />

        <el-table-column prop="total" label="总计" align="center" width="60" />

        <el-table-column label="服务项目" align="center" width="240">
          <template #default="scope">
            <label
              type="primary"
              v-for="item in scope.row.serviceList"
              :key="item.id"
              style="
                float: left;
                margin-top: 1%;
                border-radius: 5px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: nowrap;
                padding: 3px;
                border: 1px solid #a2cbf8;
                color: #135294;
                font-size: 12px;
              "
            >
              <span>{{ item.codetext }}</span>
              <text>{{ item.timewindowfrom }}</text>
            </label>
          </template>
        </el-table-column>

        <el-table-column
          prop="isCompleted"
          label="服务状态"
          align="center"
          width="100"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isCompleted == 0">
              完成
            </el-tag>
            <el-tag type="danger" v-else> 服务中 </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button
              :icon="User"
              type="primary"
              size="small"
              v-has="`btn:user:per:role`"
              @click="handleComplete(scope.row)"
              v-if="scope.row.isCompleted !== 0"
            >
              服务完成
            </el-button>
            <el-button
              :icon="User"
              type="danger"
              size="small"
              v-has="`btn:user:per:role`"
              @click="handleDel(scope.row)"
              v-if="scope.row.isCompleted !== 0"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-drawer
        v-model="innerDrawer"
        title="添加订单"
        :append-to-body="true"
        :before-close="handleClose"
        size="50%"
      >
        <el-button
          :icon="User"
          type="pr"
          v-has="`btn:user:per:role`"
          @click="handleAddOrders"
        >
          确定
        </el-button>

        <el-table
          :data="orderList"
          border
          v-loading="loading"
          style="width: 100%; margin-top: 1%"
          :header-cell-style="{ background: '#f8f9fa', color: '#1d2129' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="50" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="number"
            label="销售单号"
            width="100"
            align="center"
          />
          <el-table-column
            prop="delivery"
            label="预约时间"
            align="center"
            width="100"
          >
            <template #default="scope">
              {{ scope.row.periodsTime }}({{ scope.row.periods }})
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" align="center" />

          <el-table-column
            prop="postalCode"
            label="邮编"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="area"
            label="区域"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            prop="storeBUCode"
            label="店号"
            align="center"
            width="60"
          ></el-table-column>

          <el-table-column
            prop="totalVolume"
            label="体积"
            align="center"
            width="60"
          />
          <el-table-column
            prop="totalWeight"
            label="重量"
            align="center"
            width="70"
          />
        </el-table>
      </el-drawer>
    </el-drawer>
  </div>
</template>
  
  <script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  getDispatching,
  getDispatchingById,
  getDispatchingRevokeById,
  getDispatchingComplete,
  findPersonnelList,
  getCarPerList,
  findUpdateCarPer,
  findDispatchingAddSave,
  findDispatchingList,
  findCount,
} from "@/api/order";
import { ElMessage, ElMessageBox } from "element-plus";
const loading = ref(false);
const tableData = ref([]);
const title = ref("今日共计配送：0单；已完成：0单；剩余：$0单");

const direction = ref("rtl");
const drawer = ref(false);
const innerDrawer = ref(false);
const orderList = ref([]);

const list = ref([]);
const router = useRouter();
const id = ref(null);
const currentDate = ref("");

const seldriver = ref("");
const perList = ref([]);
const selworke = ref([]);
const details = ref({});

const carList = ref([]);

const pplist = ref([]);

const countList = ref([]);
const time = ref("");

const ordDto = ref({
  currentPage: 0,
  pageSize: 20,
  time: "",
  dispatcher: "",
  dispatchingNumber: "",
  licenseNumber: "",
  vehicleNumber: "",
  name: "",
  tel: "",
});

const perDto = ref({
  name: "",
});
onMounted(() => {
  getCurrentDate();
  find_Count();
  getPerList();
  getCarList();
  getList();
});
const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  currentDate.value = `${year}-${month}-${day}`;
  ordDto.value.time = currentDate.value;
  time.value = currentDate.value;
};

const getList = () => {
  getDispatching(ordDto.value).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      tableData.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const find_Count = () => {
  const res = {
    time: time.value,
  };
  findCount(res).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      title.value = `今日共计配送：${res.data.total} 单；已完成：${res.data.complete} 单；剩余：${res.data.incomplete} 单`;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleSearch = () => {
  getList();
};

const handleUpdateCar = () => {
  const car_temp = carList.value.find((item) => item.id === seldriver.value);
  if (car_temp) {
    details.value.licenseNumber = car_temp.licenseNumber;
    details.value.vehicleNumber = car_temp.vehicleNumber;
  }
  var arr = [];
  selworke.value.forEach((items) => {
    const newper = {
      nameId: "",
      name: "",
      position: "",
      tel: "",
    };
    const per_temp = perList.value.find((item) => item.id === items);
    newper.nameId = per_temp.id;
    newper.name = per_temp.name;
    newper.position = per_temp.officialPosition;
    newper.tel = per_temp.telephone;
    arr.push(newper);
  });
  details.value.personnels = arr;
  console.log(details.value);
  findUpdateCarPer(details.value).then((res) => {
    if (res.code === 200 && res.data !== null) {
      details.value = res.data;
      drawer.value = false;
      getList();
    }
  });
};

const getPerList = () => {
  findPersonnelList(perDto.value).then((res) => {
    if (res.code === 200 && res.data !== null) {
      perList.value = res.data;
    }
  });
};

const getCarList = () => {
  getCarPerList(perDto.value).then((res) => {
    if (res.code === 200 && res.data !== null) {
      carList.value = res.data;
    }
  });
};

const handleRole = (obj) => {
  console.log(obj);
  details.value = obj;
  drawer.value = true;
  id.value = obj.id;
  seldriver.value = obj.licenseNumber;

  var arr = [];
  obj.personnels.forEach((item) => {
    arr.push(parseInt(item.nameId));
  });
  selworke.value = arr;

  getDispatchingById(obj.id).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      list.value = res.data.data;
      pplist.value = res.data.per;
    }
  });
};

const handleDel = (obj) => {
  drawer.value = true;
  getDispatchingRevokeById(obj.id).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      var data = {
        id: details.value.id,
      };
      drawer.value = false;
      getList();
    }
  });
};

const handleComplete = (obj) => {
  drawer.value = true;
  getDispatchingComplete(id.value, obj.orderId).then((res) => {
    console.log(res);
    if (res.code === 200 && res.data !== null) {
      var data = {
        id: details.value.id,
      };
      drawer.value = false;
      getList();
    }
  });
};

const selectable = ref([]);
const handleAddOrder = () => {
  innerDrawer.value = true;
  //获取派工订单
  loading.value = true;
  const disDto = ref({
    date: "2025-05-17",
    end: "2025-05-17",
    number: "",
    goodsaddress: " 蚂蚁外仓",
  });
  findDispatchingList(disDto.value)
    .then((res) => {
      loading.value = false;
      if (res.code === 200 && res.data !== null) {
        orderList.value = res.data;
      } else {
        loading.value = false;
        orderList.value = [];
      }
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err.message);
    });
};
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  console.log(val);
  multipleSelection.value = val;
};

const handleAddOrders = () => {
  var o_data = {
    id: id.value,
    orders: multipleSelection.value,
  };
  console.log(o_data);
  findDispatchingAddSave(o_data).then((res) => {
    if (res.code === 200 && res.data !== null) {
      handleRole(id.value);
      innerDrawer.value = false;
    }
  });
};
const handleClose = (done) => {
  done();
  // ElMessageBox.confirm("Are you sure you want to close this?")
  //   .then(() => {
  //     done();
  //   })
  //   .catch(() => {
  //     // catch error
  //   });
};
</script>
<style scoped>
/*最外层透明*/
::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent !important;
}
/* 表格内背景颜色 */
::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent !important;
  border: 0;
  color: #135294;
}
/*去除底边框*/
::v-deep.el-table td.el-table__cell {
  border: 0;
}
::v-deep.el-table th.el-table__cell.is-leaf {
  border: 0;
}
/*去除底部灰条.el-table::before*/
::v-deep .el-table::before {
  display: none;
}
.el-pagination {
  text-align: center;
  justify-content: center;
  color: #135294;
}
::v-deep .el-pagination__sizes,
.el-pagination__total {
  color: #135294 !important;
}
::v-deep .el-pagination button {
  background-color: transparent !important;
}
::v-deep .el-pager li {
  background-color: transparent !important;
}
::v-deep .el-pagination button.is-disabled,
.el-pagination button:disabled {
  background-color: transparent !important;
}
::v-deep .el-pagination .el-select {
  width: 100px !important;
}
::v-deep .el-drawer__header {
  margin-bottom: 0px;
}
</style>